package com.dm.cloud.images.schedule;

import com.github.dockerjava.api.DockerClient;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.dm.cloud.images.common.po.ImagesEndpoint;
import com.dm.cloud.images.mapper.ImagesEndpointMapper;
import com.dm.cloud.images.service.ImagesEndpointService;
import com.dm.cloud.images.util.DockerUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

@Component
@Slf4j
public class NodePingTask {

    @Autowired
    private ImagesEndpointService imagesEndpointService;

    @Autowired
    private ImagesEndpointMapper imagesEndpointMapper;

    @XxlJob("nodePingHandler")
    public void nodePingHandler() throws Exception {
        XxlJobHelper.log("开始节点状态验证");
        log.debug("开始节点状态验证");
        List<ImagesEndpoint> all = imagesEndpointService.findAll();
        for (ImagesEndpoint endpoint : all) {
            DockerClient client=null;
            Integer status=0;
            try {
                client = imagesEndpointService.getClientByNodeId(endpoint.getId());
                if(DockerUtil.pingNode(client)){
                    status=1;
                }
            }catch (Exception e){
                XxlJobHelper.log(e);
                status=0;
            }finally {
                try {
                    client.close();
                }catch (Exception e){}
            }
            try {
                endpoint.setState(status);
                endpoint.setLatestTestTime(new Date());
                imagesEndpointMapper.updateByPrimaryKey(endpoint);

            }catch (Exception e){
                XxlJobHelper.log(e);
            }
            log.debug("结束节点状态验证");
        }
    }

}
